	<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page language="java" import="java.lang.*" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "com.seniorproject.aims.*" %>
<%@ page import = "java.util.List" %>
<%@page import="java.util.ArrayList"%>
<%@ page import = "java.util.Properties" %>
<%@ page import = "javax.servlet.ServletContext" %>
<%@ page import = "java.io.File" %>
<%@ page import = "java.io.InputStream" %>


<html>
<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>Student Add</title>
		<link rel="stylesheet" type="text/css" href="css/stylev2.css" />
		<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
		<script type="text/javascript" src="js/bootbox.js"></script>
		
		<style type="text/css">
			 a:hover {
			  	cursor:pointer;
			 }
			 a {
		      text-decoration:none;
		   	}
		</style>
	
<script>

$(document).ready(function(){

	$("#frm_add_manual").hide();
	$("#frm_add_file").hide();
	
	 $("#btn_add_file").click(function(){
	 
		 
			$("#frm_add_manual").hide();
			$("#frm_add_file").show();
	 });
	 
	 $("#btn_add_manual").click(function(){
	 	
		 $("#frm_add_file").hide();
		$("#frm_add_manual").show();
			
		 
	 });
	
	
	
});

function onSelectBoxChange(id) {
	
    //var x = document.getElementById("department").value;
    //alert("Now Select is:"+id);////////////try///////////////
    
    var sql = " AND D.department_id="+id;
    
    /* AJAX */
	var xmlhttp;
	
	if(window.XMLHttpRequest) {
		// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp = new XMLHttpRequest();
	}
	else {
		// code for IE6, IE5
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	xmlhttp.onreadystatechange = function() {
		if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {									
		
			//alert("I'm back");///////////////try///////////
			var result = xmlhttp.responseText;
			
			var jsonObj = JSON.parse(xmlhttp.responseText);
			
			if($('#curriculum').find('option').length > 0) {					
				$('#curriculum').find('option').remove();
			}
			
			if(jsonObj.length == 0) {
				
				text = '<option value="select">โปรดเลือกหลักสูตร</option>';
				
				$('#curriculum').append(text);
				
				alert("ไม่พบข้อมูล");
				
			}
			else{
				for(i in jsonObj) {
					text = '<option value="'+jsonObj[i].curriculumId+'">'+jsonObj[i].curriculumNameTH+' ('+jsonObj[i].year+')</option>';
					
					$('#curriculum').append(text);
				}
			}
		}
	}
	
	xmlhttp.open("POST", "curriculum_search_background.jsp?sql_con="+sql, true);
	xmlhttp.send();
}

function isValidUploadForm(oForm){
	
	//alert("Active isValidUploadForm");
	
	var _validFileExtensions = [".xlsx", ".xls"];
	  var arrInputs = oForm.getElementsByTagName("input");
	 
	  
	//  alert("arrInputs:"+ oForm.getElementsByTagName("input")[0].value);
	  
	  var file_name =  oForm.getElementsByTagName("input")[0].value
	  	if(file_name=="")
	  	{
	  		alert("กรุณาเลือกไฟล์ที่จะทำการ Import ในรูปแบบ xls, xlsx");
	  		return false;
	  	}
	  
	    for (var i = 0; i < arrInputs.length; i++) {
	        var oInput = arrInputs[i];
	        if (oInput.type == "file") {
	            var sFileName = oInput.value;
	            if (sFileName.length > 0) {
	                var blnValid = false;
	                for (var j = 0; j < _validFileExtensions.length; j++) {
	                    var sCurExtension = _validFileExtensions[j];
	                    if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
	                        blnValid = true;
	                        break;
	                    }
	                }

	                if (!blnValid) {
	                    alert("เกิดข้อผิดพลาด " + sFileName + " ไฟล์ที่แนบไม่ตรงรูปแบบของ : " + _validFileExtensions.join(", "));
	                    return false;
	                }
	            }
	        }
	    }

	    return true;
	
	
	
}

function isValidForm(){
	//alert("Active");
	
	var sel_department = document.getElementById("department").value;
	var sel_curriculum = document.getElementById("curriculum").value;
	
	//alert(sel_department+":"+sel_curriculum);

	
	
	if(sel_department=="select" || sel_curriculum=="select")
	{
		alert("กรุณาเลือก ภาควิชาและหลักศูตร");
		return false;
		
	}
	else{
		return true;
	}
	
}


</script>


</head>
<body>

<%
	String strUser = String.valueOf(session.getAttribute("sUser"));
	HttpSession htp_session = request.getSession();
			
	if (htp_session == null || htp_session.getAttribute("sUser") == null) {
	    // Forward the control to login.jsp if authentication fails or session expires
	    request.getRequestDispatcher("/login.jsp").forward(request,
	        response);
	}
	
	if("admin".equals(htp_session.getAttribute("sUser"))){%>
	<script>alert("This user dont have PERMISSION to access this zone.");</script>
	<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=admin_home.jsp"> 	
	<%}
	
//////////get permission ///////////
	
	String name = String.valueOf(session.getAttribute("name"));
	String surname = String.valueOf(session.getAttribute("surname"));
	String role_name = String.valueOf(session.getAttribute("student_role"));
	
	String department_id = String.valueOf(session.getAttribute("department_id"));

	System.out.println("name : " + name);///////////////////////////////
	System.out.println("department_id : " + department_id);/////////////////////////
	
	
	List<String> system_name = new ArrayList<String>();
	
	Permission permission = new Permission(strUser,name);
	permission.setDepartmentId(department_id);
	permission.setStudentCreate(Boolean.valueOf(String.valueOf(session.getAttribute("student_create"))));
	permission.setStudentDelete(Boolean.valueOf(String.valueOf(session.getAttribute("student_delete"))));
	permission.setStudentRead(Boolean.valueOf(String.valueOf(session.getAttribute("student_read"))));
	permission.setStudentUpdate(Boolean.valueOf(String.valueOf(session.getAttribute("student_update"))));
	
	String permiss = "";
	if(permission.getStudentCreate()) {
		permiss = permiss + "Add";
	}
	if(permission.getStudentUpdate()) {
		if("".equals(permiss)) {
			permiss = permiss + "Edit";
		} else {
			permiss = permiss + " Edit";
		}
	}
	if(permission.getStudentRead()) {
		if("".equals(permiss)) {
			permiss = permiss + "Read";
		} else {
			permiss = permiss + " Read";
		}
	}
	if(permission.getStudentDelete()) {
		if("".equals(permiss)) {
			permiss = permiss + "Delete";
		} else {
			permiss = permiss + " Delete";
		}
	}
	//check permission
	if(!permission.getStudentCreate()){%>
		<script>alert("This user dont have PERMISSION to access this zone.");</script>
		<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=student_home.jsp"> 	
	<%}
			
	//set Database Connection
		String hostProps = "";
		String usernameProps  = "";
		String passwordProps  = "";
		String databaseProps = "";
		
		try {
			//get current path
			ServletContext servletContext = request.getSession().getServletContext();
			
			InputStream input = servletContext.getResourceAsStream("/properties/connectDB.properties");
			Properties props = new Properties();
			
			props.load(input);

			hostProps  = props.getProperty("host");
			usernameProps  = props.getProperty("username");
			passwordProps  = props.getProperty("password");
			databaseProps = props.getProperty("database");
		} catch (Exception e) { 
			out.println(e);  
		}
		
		// connect database
		Connection connect = null;		
		try {
			Class.forName("com.mysql.jdbc.Driver");
		
			connect =  DriverManager.getConnection("jdbc:mysql://" + hostProps  + "/" + databaseProps +
					"?user=" + usernameProps  + "&password=" + passwordProps + "&characterEncoding=tis620" );
		
			if(connect != null){
				System.out.println("Database Connect Sucesses.");
			} else {
				System.out.println("Database Connect Failed.");	
			}

		} catch (Exception e) {
			out.println(e.getMessage());
			e.printStackTrace();
		}
		
		
		/* find department in database */
		List<Department> department = new ArrayList<Department>();
		List<Curriculum> curriculum = new ArrayList<Curriculum>();
		
		try {			   
			ResultSet rs_department;
			if(("0").equals(permission.getDepartment_id()))
			{
				  rs_department = connect.createStatement().executeQuery("SELECT department_id, department_name_th " 
							+ " FROM department " + " ORDER BY department_id");
			}
			else{
				  rs_department = connect.createStatement().executeQuery("SELECT department_id, department_name_th " 
							+ " FROM department " 
						    +" WHERE department_id="+permission.getDepartment_id()
						    );
			}
			
			
			while(rs_department.next()) {
				Department dep = new Department();
				
				dep.setDepartmentNameTH(rs_department.getString("department_name_th"));
				dep.setDepartmentId(Integer.parseInt(rs_department.getString("department_id")));
				
				department.add(dep);
			}
			
			//////////////////////////////////////////////////////////////////////////////////////////////
			ResultSet rs_curriculum = null;
			
/*			if("0".equals(department_id)) {		
				rs_curriculum = connect.createStatement().executeQuery("SELECT curriculum_id, curriculum_name_th , year "
					+ " FROM curriculum "  
					+  " ORDER BY curriculum_id");
			}
			else {
*/				rs_curriculum = connect.createStatement().executeQuery("SELECT curriculum_id, curriculum_name_th , year "
						+ " FROM curriculum "  
						+  " WHERE department_id='"+department_id+"'"
						+  " ORDER BY curriculum_id");
//			}
			
			while(rs_curriculum.next()){
				Curriculum curr = new Curriculum();
				
				curr.setCurriculumId(Integer.parseInt(rs_curriculum.getString("curriculum_id")));
				curr.setCurriculumNameTH(rs_curriculum.getString("curriculum_name_th"));
				curr.setYear(rs_curriculum.getString("year"));
				
				curriculum.add(curr);
				
			}

			
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
	
		connect.close();

%>



<div id="page-wrap">
		<div id="inside">
			<table border="0">
				<tr style="font-size:24px">
					<td width="600" height="100" style= "background-color: #273b80;border: 0px ;padding: 0px; 0px;" >
						<div id="header_banner-2"></div>
					</td>
					
					<td width="680" height="100" style= "background-color: #273b80;border: 0px;padding: 0px; 0px;" >
						<p align="right"><label><font size="4" color="#ffffff">username : <%=strUser%>&nbsp;&nbsp;</font></label></p>
						<a href="logout.jsp"><p align="right"><label style="cursor: pointer;"><font size="3" color="#ffffff">log out &nbsp;</font></label></p></a>
					</td>
				</tr>
			</table>
			<table border="0">
				<tr style="font-size:10px">
					<td width = "720" height="50" style= "background-color:#D0D0D0 ;">
						<center><a href="student_home.jsp"><h2><font color="#273b80"><label style="cursor: pointer;">หน้าแรก</label></font></h2></a></center>
					</td>
	<%
			if(permission.getStudentRead()) {
	%>
					<td width = "720" height="50" style= "background-color:#D0D0D0 ;">
						<center><a href="student_search.jsp"><h2><font color="#273b80"><label style="cursor: pointer;">ค้นหา</label></font></h2></a></center>
					</td>
					<td width = "720" height="50" style= "background-color:#D0D0D0 ;">
						<center><a href="student_summary.jsp"><h2><font color="#273b80"><label style="cursor: pointer;">สรุปจำนวนนักศึกษา</label></font></h2></a></center>
					</td>
	<%
			}
			if(permission.getStudentCreate()) {
	%>
					<td width = "720" height="50" style= "background-color:#FFFFFF ; border-bottom-color: #FFFFFF;">
						<center><a href=""><h2><font color="#273b80"><label>เพิ่มนักศึกษา</label></font></h2></center>
					</td>
	<%
			}
			
			if(permission.getStudentUpdate()) {
	%>
					<td width = "720" height="50" style= "background-color:#D0D0D0 ;">
						<center><a href="student_edit.jsp"><h2><font color="#273b80"><label style="cursor: pointer;">แก้ไขข้อมูล</label></font></h2></a></center>
					</td>
	<%
			}
	%>
				</tr>
			</table>
				
				<div id="main-content-ac">
					
		<!-- 		<h2 style="padding-left: 2.5cm; color: #273b80;">เพิ่มข้อมูล</h2>	 -->
		
				<br><br>
				<center>
						<table>
							<tr>
								<td>
									<button name="add_file" id="btn_add_file" style= "height: 40px; width: 140px; font-size:medium;">เพิ่มด้วยไฟล์ Microsoft Excel</button>
								</td>
								<td>	
									<button name="add_manual" id="btn_add_manual" style= "height: 40px; width: 140px; font-size:medium;">เพิ่มนักศึกษาทีละคน</button>
								</td>	
							</tr>
						</table>
					</center>
					<br><br>
					
				<center>
				<div id="frm_add_manual">
					<form name="frm_student_add" method="post" action="student_add_2.jsp" onsubmit="return isValidForm()">	
							<table width="300" border="0">
			             	 <tbody>
			             	<tr style="font-size:28px">
			               	<td width="248" height="50">ภาควิชา</td>
							<td width="236">
			                        <select id="department" onchange="onSelectBoxChange(this.value)" name="department" style="font-size:18px">
			                        
			                            <option value="select">Select</option>
			                         	
			                         	<%
			                         		int num = department.size();
			                       
			                         		for(int i =0;num>0;num--,i++)
			                         		{
			                         			if(department.get(i).getDepartmentId() == 0) {}
			                         			else {
			                         			%>
			                         			 <option value="<%= department.get(i).getDepartmentId()%>"><%= department.get(i).getDepartmentNameTH() %></option>
			                         			
			                         			<% 
			                         			}
			                         		}
			                         	%>
			                         
			                         	</select>
			                         	
			                        
			                </td>
			              </tr>
			              
			              <tr style="font-size:28px">
			             	<td width="248" height="50">หลักสูตร</td>
							<td>
			                	  <select id="curriculum"  name="curriculum" style="font-size:18px">
			                	  	<option value="select">โปรดเลือกหลักสูตร</option>
			                	  	
			                	  	
			                         	<%
			                         		int num_curr = curriculum.size();
			                         	
			                       			System.out.println("num_curr "+num_curr);///try//
			                       			
			                         		for(int i =0;num_curr>0;num_curr--,i++)
			                         		{
			                         			
			                         			%>
			                         			 <option value="<%= curriculum.get(i).getCurriculumId()%>"><%= curriculum.get(i).getCurriculumNameTH() %> (<%=curriculum.get(i).getYear() %>)</option>
			                         			
			                         			<% 
			                         			
			                         		}
			                         	%>
			                	  
			                	  	
			                       </select>
			                </td>
			              </tr>
			              
			              <tr style="font-size:28px">
			             	<td width="248" height="50" colspan="2">
			                	<center><button name="nextBut" id="nextBut" style= "height: 40px; width: 60px; font-size:medium;">ถัดไป</button></center>
			                </td>
			              
			              </tr>
			             
						</tbody></table>
					</form>
				</div>
				
				<div id="frm_add_file">
					
					<table>
						<tr>
							<td>
								<center>
									 <form method="post" onsubmit="return isValidUploadForm(this);	" action="UploadServlet"enctype="multipart/form-data">
			        		  			 เลือกไฟล์ <input id="file_box" type="file" name="uploadFile"> 
			        		  			 <br>
			        		  			 <br>
			        		  			 <br>
			        		  			 
			        		  			 <input type="submit" value="Upload" />
			        		  			 
			        		  			 <br>
			        		  			 </form>
			        		  			 
			        		  	</center>
			        		 </td>
			        		 
	        		  		 
						</tr>
							
					</table>
				
				</div>
				
				
			</center>
			<br><br><br><br><br><br><br><br><br><br><br><br>
							
				
			<div style="clear: both;"></div>
				
			<div id="footer"></div>
			
		</div>		
			<div style="clear: both;"></div>		
   </div>



</body>
</html>